﻿using System;
using System.Text.RegularExpressions;

namespace Cms.Utilities
{
    public class Version
    {
        private readonly int _build;
        private readonly string _full;
        private readonly int _major;
        private readonly int _minor;
        private readonly int _revision;

        public Version(string versionInfo)
        {
            var pattern = new Regex("[0-9]+");
            MatchCollection matches = pattern.Matches(versionInfo);
            if (matches.Count != 4)
                throw new Exception(string.Format("Version number {0} has incorrect format.", versionInfo));
            _major = int.Parse(matches[0].Value);
            _minor = int.Parse(matches[1].Value);
            _build = int.Parse(matches[2].Value);
            _revision = int.Parse(matches[3].Value);
            _full = versionInfo;
        }

        public int Major
        {
            get { return _major; }
        }

        public int Minor
        {
            get { return _minor; }
        }
        
        public int Build
        {
            get { return _build; }
        }
        
        public int Revision
        {
            get { return _revision; }
        }
        
        public string Full
        {
            get { return _full; }
        }
        
        public bool IsGreaterThan(Version v)
        {
            if (_major < v.Major)
                return false;
            if (_major > v.Major)
                return true;

            // The major parts are the same
            if (_minor < v.Minor)
                return false;
            if (_minor > v.Minor)
                return true;

            // The minor parts are the same
            if (_build < v.Build)
                return false;
            if (_build > v.Build)
                return true;

            // The build parts are the same
            return _revision > v.Revision;
        }
        
        public bool IsLessThanOrEqualTo(string version)
        {
            var otherVersion = new Version(version);
            return !IsGreaterThan(otherVersion);
        }
    }
}